package com.party.admin.web.controller.excel;

import com.party.admin.biz.excel.ExcelAnalyzeBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * 表格控制器
 *
 * @author yifeng
 * @date 2018/6/12 0012
 * @time 下午 15:06
 */
@Controller
@RequestMapping("/excel/excel")
public class ExcelController {
    @Autowired
    private ExcelAnalyzeBizService excelAnalyzeBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping("toImportExcel")
    public ModelAndView toImportExcel() {
        return new ModelAndView("/excel/excelAnalyze");
    }

    /**
     * 导入Excel
     *
     * @param uploadFile 文件
     */
    @ResponseBody
    @RequestMapping("importExcel")
    public AjaxResult importExcel(MultipartFile uploadFile) {
        try {
            excelAnalyzeBizService.importExcel(uploadFile);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("导入Excel异常", e);
            return AjaxResult.error("导入Excel异常");
        }
    }

    /**
     * 分析表格数据
     *
     * @param blockNum 段号
     * @param rowNums  行号
     * @param colNums  列号
     * @param fields   字段
     * @return
     */
    @ResponseBody
    @RequestMapping("analyzeExcel")
    public AjaxResult analyzeExcel(String blockNum, String rowNums, String colNums, String fields) {
        if (StringUtils.isEmpty(blockNum)) {
            return AjaxResult.error("请输入表格段数");
        }
        if (StringUtils.isEmpty(fields)) {
            return AjaxResult.error("请输入字段");
        }
        try {
            Map<String, Map<String, Object>> datas = excelAnalyzeBizService.analyzeExcel(blockNum, rowNums, colNums, fields);
            return AjaxResult.success(datas);
        } catch (BusinessException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("计算数据异常", e);
            return AjaxResult.error("计算数据异常");
        }
    }
}
